package net.maku.jw.util;

import com.alibaba.excel.util.StringUtils;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import net.maku.jw.entity.Course;
import net.maku.jw.entity.Student;
import net.maku.jw.entity.SysMember;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static net.maku.jw.util.StudentCourseJsoupUtil.getcourseTable;

public class HtmlunitUtil {
    private static WebClient client=null;
    private static HtmlPage page=null;

    static String  startDate = "2023/09/04"; //开学日期   y/m/d
    static String  xueqi = "2023-2024-1"; //学期


    static {
        client=new WebClient(BrowserVersion.CHROME);//设置浏览器内核
        client.getCookieManager().setCookiesEnabled(true);//设置cookie是否可用
        client.getOptions().setJavaScriptEnabled(true); // js是否可用
        client.getOptions().setThrowExceptionOnScriptError(true); //忽略js错误
        client.getOptions().setTimeout(30000);//超时时间10S
        client.getOptions().setCssEnabled(false); //css 一般设置false因为影响运行速度
        client.setAjaxController(new NicelyResynchronizingAjaxController()); // ajax设置
        client.getOptions().setThrowExceptionOnFailingStatusCode(false);
        client.getOptions().setUseInsecureSSL(true);  //6 设置忽略证书
        client.getOptions().setRedirectEnabled(true); //允许重定向！

    }

    public static SysMember login(SysMember member) throws Exception {
        long time = System.currentTimeMillis();
        InitLogin(member);
        CookieManager CM = client.getCookieManager();
        client.close();//关闭客户端用于释放内存
        String tooken = HtmlUtil.cookieToString(CM);

        if (!StringUtils.isEmpty(tooken)) {
            System.out.println("获取cookie耗时："+(System.currentTimeMillis()-time));
            member.setIsBind(1);
            member.setToken(tooken);
        }
        return member;
    }


    //解析验证码
    public static String CAPTCHA (HtmlPage page) throws Exception {
        HtmlImage imgstr = page.getHtmlElementById("SafeCodeImg"); // 获取图片代码
        File file = new File("D:\\certs\\manage.jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        imgstr.saveAs(file);  //保存验证码
        OcrUtils.init();// 初始化验证码识别模型
        BufferedImage image = ImageIO.read(file);
        System.out.println("正在识别验证码...");
        String code = OcrUtils.discernImg(image);// 开始识别
        System.out.println(code);
        return code;
    }

    /**
     * 获取全部课表  默认第一周课表
     * @return
     * @throws IOException
     */
    public static List<Course> getCourseList(SysMember member,String team) throws Exception {
        List<Course> result = new ArrayList<>();
        page = client.getPage("http://10.20.208.51/jsxsd/xskb/xskb_list.do");
        String title = page.getTitleText().trim();
        if ("登录".equals(title)){
            InitLogin(member);
            page = client.getPage("http://10.20.208.51/jsxsd/xskb/xskb_list.do");
            client.waitForBackgroundJavaScript(2500);
        }
        //限死 上学期的课表，因为本学期没有课！    选取全部课表下面代码不用运行     这里卡顿次数多
        HtmlSelect xnxq01id = (HtmlSelect) page.getElementById("xnxq01id");
        xnxq01id.setSelectedAttribute(xnxq01id.getOptionByValue("2023-2024-1"),true);
        HtmlPage htmlpage = xnxq01id.click();
        //System.out.println(htmlpage.asXml());
        client.waitForBackgroundJavaScript(2500);
        //"默认第一周"   不再运行此逻辑： 因为课表保存数据库逻辑了。
        /*HtmlSelect zc = (HtmlSelect) htmlpage.getElementById("zc");
        HtmlOption optionByValue = zc.getOptionByValue("1");
        zc.setSelectedAttribute(optionByValue,true);
        htmlpage = zc.click();
        client.waitForBackgroundJavaScript(2500);*/
        //解析课表html
        //点击 单选框 有课表课程
        //input[type='radio']:nth-of-type(2) 选择<input>类型为radio的第二个同级兄弟元素
        //table.myClass > :nth-child(2)   选择class为myClass的div元素的第二个子元素
//        HtmlElement element = page.querySelector("table > input[name=kblx]:nth-of-type(2)");
//        System.out.println(element.getTextContent());
//        System.out.println("-------------------------------------");
//        htmlpage = element.click();
//        client.waitForBackgroundJavaScript(2000);
        String s = htmlpage.asXml();
        if (!"".equals(s)){
            System.out.println("正在解析。。。");
            result = getcourseTable(s,member.getUseraccount(),team);
        }
        return result;
    }

    public static void InitLogin(SysMember member) throws Exception {
        page = client.getPage("http://10.20.208.51/jsxsd/");
        String code = CAPTCHA(page);
        HtmlElement user = page.querySelector("input[id=userAccount]"); //获取用户名输入框
        user.setAttribute("value", member.getUseraccount());//在页面中添加你的登录账号
        HtmlElement pwd = page.querySelector("input[id=userPassword]"); // 获取密码输入框
        pwd.setAttribute("value",member.getUserpwd());

        HtmlElement yzm = page.querySelector("input[id=RANDOMCODE]"); // 图片验证码
        yzm.setAttribute("value", code);
        HtmlElement btn = page.querySelector("a[id=btn-login]"); //登录按钮
        HtmlPage htmlPage = btn.click(); //点击
        client.waitForBackgroundJavaScript(2500);//等待页面上所有的 JavaScript 代码执行完毕。这个方法在处理异步 JavaScript 代码时非常有用
    }



    public static SysMember getStudentInfo(SysMember sysMember) throws Exception {

        //InitLogin initLogin = new InitLogin();
        //sysMember = login(sysMember);
        page = client.getPage("http://10.20.208.51/jsxsd/grxx/xsxx");
        client.waitForBackgroundJavaScript(2000);
        String response = page.asXml();
        // 测试cache登录 是否有效 todo  studentInfo并没有更新进去，
        Student studentInfo = HtmlUtil.getStudentInfo(response);
        sysMember.setGender(studentInfo.getStudentSex().equals("男") ? 0 : 1);
        sysMember.setStudent(studentInfo);
        System.out.println("有没有更新进去" + sysMember.getStudent().toString());
        return sysMember;
    }

    public String getcodeByPeople() throws IOException {
        page = client.getPage("http://10.20.208.51/");
        HtmlImage imgstr = page.getHtmlElementById("SafeCodeImg"); // 获取图片代码
        String aa = imgstr.getSrcAttribute();
        String bb="http://10.20.208.51"+aa;
        //图片保存本地
        File file = new File("D:\\certs\\manage.jpg");  //todo 改成项目文件夹位置
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        imgstr.saveAs(file);  //保存验证码
        return bb;
    }





}
